package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.company.bean.EnumManage;
import com.fz.us.admin.company.entity.Admin;
import com.fz.us.admin.company.service.AdminService;
import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/14.
 */
@Controller
@RequestMapping(value = "/com/personnelInfo")
public class PersonnelInfoController extends BaseController {
    private static final long serialVersionUID = 2497897211231359969L;

    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;


    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            PersonnelInfo personnelInfo=personnelInfoService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("personnelInfo", personnelInfo);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelInfo_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            PersonnelInfo personnelInfo=personnelInfoService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("personnelInfo", personnelInfo);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelInfo_read";
    }

    /**
     * 保存Model数据
     */
    private PersonnelInfo saveModel(User user, String keyId, String name, String sex,String month,
                                    String cardId, String deptId, String postId, String phone,String email) {

        PersonnelInfo personnelInfo = null;
        if (StringUtils.isBlank(keyId)) {
            personnelInfo = new PersonnelInfo();
            personnelInfo.setCreater(user);
            personnelInfo.setCompany(user.getCompany());
        } else {
            personnelInfo = personnelInfoService.get(keyId);
        }
        if(StringUtils.isNotEmpty(name)){
            personnelInfo.setName(name);
        }
        if(StringUtils.isNotEmpty(sex)){
            personnelInfo.setSex(Integer.parseInt(sex));
        }
        if(StringUtils.isNotEmpty(cardId)){
            personnelInfo.setCardId(cardId);
        }
        if(StringUtils.isNotEmpty(deptId)){
            personnelInfo.setDepartment(departmentService.get(deptId));
        }
        if(StringUtils.isNotEmpty(postId)){
            personnelInfo.setPost(postService.get(postId));
        }
        if(StringUtils.isNotEmpty(phone)){
            personnelInfo.setPhone(phone);
        }
        if(StringUtils.isNotEmpty(email)){
            personnelInfo.setEmail(email);
        }
//        if(StringUtils.isNotEmpty(month)){
        personnelInfo.setMonth(13);
//        }

        return personnelInfo;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String name,
                       String sex,
                       String month,
                       String cardId,
                       String deptId,
                       String postId,
                       String phone,
                       String email) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelInfo personnelInfo = saveModel(user, keyId, name, sex, month, cardId, deptId, postId, phone, email);

        if(StringUtils.isNotEmpty(keyId)){
            personnelInfoService.update(personnelInfo);
            rMap.put("message", "更新成功");
        } else {
            personnelInfoService.save(personnelInfo, "com.fz.us.oa.core.entity.com.PersonnelInfo");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String name,
                         String sex,
                         String month,
                         String cardId,
                         String deptId,
                         String postId,
                         String phone,
                         String email,
                         String curDutyId,
                         String comment) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelInfo personnelInfo = saveModel(user, keyId, name, sex, month, cardId, deptId, postId, phone, email);

        if (StringUtils.isNotEmpty(keyId)) {
            personnelInfoService.approve(personnelInfo, dutyService.get(curDutyId), comment);
        } else {
            personnelInfoService.commit(personnelInfo, "com.fz.us.oa.core.entity.com.PersonnelInfo", dutyService.get(curDutyId));
        }

        //如果归档
        if(personnelInfo.getProcessState().name().equals("Finished")){
            //注册新用户步骤
//            String phone=personnelInfo.getPhone();
//            String name=personnelInfo.getName();
            Company company = user.getCompany();
            String password="password";
            Result result = userService.validateAccount(phone);
            if(result.getState() == 0) {
                return ajaxJson(resultService.fail("请输入有效的手机号/邮箱账号, 或已被使用！"));
            } else {
                EnumManage.AccountEnum accountType = (EnumManage.AccountEnum)result.getData();
                Admin admin = adminService.createAdmin(accountType, EnumManage.AccountTypeEnum.User, phone, password);
                if(admin != null) {
                    User newUser = userService.createUser(name, admin.getId(), company);
                    personnelInfo.setUser(newUser);

                    //添加这个用户的职责
                    Duty duty=new Duty();
                    Power power=personnelInfoService.getPowerByDepartmentAndPost(personnelInfo.getDepartment(), personnelInfo.getPost());
                    System.out.println("#####powerId:"+power.getId());
                    duty.setPower(power);
                    duty.setUser(newUser);
                    dutyService.createEntity(newUser, duty);

                } else {
                    return ajaxJson(resultService.fail("新增成员失败！"));
                }
            }
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelInfo personnelInfo = personnelInfoService.get(keyId);
        personnelInfoService.approve(personnelInfo, dutyService.get(curDutyId), comment);

        //如果归档
        if(personnelInfo.getProcessState().name().equals("Finished")){
            //注册新用户步骤
            String phone=personnelInfo.getPhone();
            String name=personnelInfo.getName();
            Company company = user.getCompany();
            String password="password";
            Result result = userService.validateAccount(phone);
            if(result.getState() == 0) {
                return ajaxJson(resultService.fail("请输入有效的手机号/邮箱账号, 或已被使用！"));
            } else {
                EnumManage.AccountEnum accountType = (EnumManage.AccountEnum)result.getData();
                Admin admin = adminService.createAdmin(accountType, EnumManage.AccountTypeEnum.User, phone, password);
                if(admin != null) {
                    User newUser = userService.createUser(name, admin.getId(), company);
                    personnelInfo.setUser(newUser);

                    //添加这个用户的职责
                    Duty duty=new Duty();
                    Power power=personnelInfoService.getPowerByDepartmentAndPost(personnelInfo.getDepartment(), personnelInfo.getPost());
                    System.out.println("#####powerId:"+power.getId());
                    duty.setPower(power);
                    duty.setUser(newUser);
                    dutyService.createEntity(newUser, duty);

                } else {
                    return ajaxJson(resultService.fail("新增成员失败！"));
                }
            }
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelInfo personnelInfo = personnelInfoService.get(keyId);
            personnelInfoService.back(personnelInfo, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelInfo personnelInfo = personnelInfoService.get(keyId);
            personnelInfoService.deny(personnelInfo, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表、员工生日一览
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //正式员工
                params.put("nature", 1);
                params.put("quit", false);
                searchResult = personnelInfoService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.PersonnelInfo", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("2")){
                //试用员工
                params.put("nature",2);
                params.put("quit", false);
                searchResult = personnelInfoService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.PersonnelInfo", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //即将到期员工
                params.put("expire", true);
                params.put("quit", false);
                searchResult = personnelInfoService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.PersonnelInfo", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("4")){
                //离职员工
                params.put("quit", true);
                searchResult = personnelInfoService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.PersonnelInfo", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = personnelInfoService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.PersonnelInfo",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<PersonnelInfo> personnelInfoList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(PersonnelInfo personnelInfo: personnelInfoList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(personnelInfo.getId())?"":personnelInfo.getId());
            rMap.put("name", StringUtils.isEmpty(personnelInfo.getName())?"":personnelInfo.getName());

            int year=Integer.parseInt(personnelInfo.getCardId().substring(6,10));
            int thisYear=Integer.parseInt(DataUtil.DateToString(new Date(),"yyyy"));
            rMap.put("age",thisYear-year);
            rMap.put("sex",personnelInfo.getSex()==1?"男":"女");
            rMap.put("department",personnelInfo.getDepartment().getName());
            rMap.put("post",personnelInfo.getPost().getName());
            rMap.put("phone",personnelInfo.getPhone());
            if(personnelInfo.getNature()==1){
                rMap.put("nature","正式员工");
            }else if(personnelInfo.getNature()==2){
                rMap.put("nature","试用员工");
            }else{
                rMap.put("nature","暂无");
            }
            rMap.put("creater", personnelInfo.getCreater()==null?"": personnelInfo.getCreater().getName());
            rMap.put("processStateName", personnelInfo.getProcessState()==null?"": personnelInfo.getProcessState().value());
            rMap.put("createTime", personnelInfo.getCreateTime()==null?"": DataUtil.DateTimeToString(personnelInfo.getCreateTime()));
            if(personnelInfo.getPersonnelSelf()==null){
                rMap.put("month","--");
                rMap.put("birthday","未填写");
            }else{
                rMap.put("month",personnelInfo.getMonth()+"月");
                rMap.put("birthday",DataUtil.DateToString(personnelInfo.getPersonnelSelf().getBirthday(),"yyyy-MM-dd"));
            }
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 选择岗位
     */
    @RequestMapping(value = "dialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialog(@CurrentUser User user, Model model,
                         String departmentId,String multi) {

        model.addAttribute("departmentId", departmentId);
        model.addAttribute("multi", multi);
        return "/com/post_dialog";
    }

    /**
     * tree
     */
    @RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Map<String, Object>> tree(@CurrentUser User user,
                                          @RequestParam(required = false) String departmentId) {
        List<Power> powerList = null;
        ArrayList<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if(StringUtils.isNotEmpty(departmentId)){
            Department department=departmentService.get(departmentId);
            powerList=personnelInfoService.getPowerByDepartment(department);

            for(Power power:powerList){
                Map<String, Object> map = personnelInfoService.getTreeMap(power);
                mapList.add(map);
            }
        }

        return mapList;
    }

    /**
     * 登录页注册
     */
    @RequestMapping(value = "newReg",method = RequestMethod.POST)
    public Object newReg(@RequestParam String name,String account,String password){
        Result result = userService.validateAccount(account);
        if(result.getState() == 0) {
            return ajaxJson(resultService.fail("请输入有效的手机号/邮箱账号, 或已被使用！"));
        }else{
            EnumManage.AccountEnum accountType = (EnumManage.AccountEnum)result.getData();
            Admin admin = adminService.createAdmin(accountType, EnumManage.AccountTypeEnum.User, account, password);
            if(admin != null) {
                Company company = adminService.getCompanyByAdminType();
                User user=userService.createUser(name, admin.getId(), company);
                if(user==null){
                    return ajaxJson(resultService.fail("注册失败"));
                }
            }
        }
        return ajaxJson(resultService.success("注册成功"));
    }

}
